<?php

namespace Admin\Model;

use Think\Model;
use Admin\Model\TagModel;

class SiteModel extends Model {

	/**
	 * 保存数据:当$id为空时添加数据;不为空则更新数据
	 *
	 * @param array $data
	 * @param string $id
	 */
	public function saveData($data, $id = '') {
		$id = intval ( $id );
		$this->error = false;
		$tag = new TagModel ();
		if ($data ['context'] != '') {
			$data ['context'] = str_replace (array("<p><p>","<p><br/></p>"), '', $data ['context'] );
			$data ['context'] = str_replace ( array (
					'<br>',
					'<br/>',
					'<br />'
			), '<p>', $data ['context'] );
		}
		if ($id) {
			// 编辑
			if ($data ['name'] != '') {
				$_data ['name'] = $data ['name'];
			}
			if ($data ['url'] != '') {
				$_data ['url'] = $data ['url'];
				if (! eregi ( "^[a-z]+[a-z0-9]+$", $data ['url'] )) {
					$result ['status'] = 0;
					$result ['msg'] = 'url必须是字母开头,后面只能跟字母和数字!';
				} else if ($this->checkUrl ( $data ['url'], $data ['id'] )) {
					$result ['status'] = 0;
					$result ['msg'] = 'url已经存在';
				}
			}

			if ($data ['thumb'] != '') {
				$_data ['thumb'] = $data ['thumb'];
			}
			if ($data ['keyword'] != '') {
				$tags = make_tags ( $data ['keyword'] );
				$_data ['keyword'] = $tags ['str'];
			}
			if ($data ['intro'] != '') {
				$_data ['intro'] = cut_str ( $data ['intro'], 200 );
			}
			if ($data ['photo'] != '') {
				$_data ['photo'] = $this->_clearPhoto ( $data ['photo'] );
			}
			if ($data ['context'] != '') {
				$_data ['context'] = strip_tags ( preg_replace ( '/\s+style\=\"[^\"]*"/i', '', $data ['context'] ), '<p>,<strong>,<img>,<em>,<b>' );
				$_data ['context'] = preg_replace ( '/\s+(?:height|width)=\d+\b/', '', $_data ['context'] );
			}

			if ($data ['name'] != '') {
				$_data ['name'] = $data ['name'];
			}
			if ($data ['cid'] != '') {
				$_data ['cid'] = $data ['cid'];
			}
			if ($result ['status'] != '0') {
				$_data ['updatetime'] = date ( 'Y-m-d H:i:s' );
				$rs = $this->where ( 'id=' . $id )->save ( $_data );
				if ($rs) {
					if ($data ['keyword'] != '') {
						// 删除所有tag
						$tag->deleteDate ( $id, 'site' );

						// 添加标签
						$tag->saveData ( $tags ['tags'], $id, 'site' );
					}

					// 清除缓存
					$this->_clearInfoCache ( $id );

					$result ['status'] = 1;
					$result ['msg'] = '保存成功';
				} else {
					$result ['status'] = 0;
					$result ['msg'] = '没有更新数据';
				}
			}
		} else {
			// 新增
			if (! eregi ( "^[a-z]+[a-z0-9]+$", $data ['url'] )) {
				$result ['status'] = 0;
				$result ['msg'] = 'url必须是字母开头,后面只能跟字母和数字';
			} elseif (! $data ['name']) {
				$result ['status'] = 0;
				$result ['msg'] = '名称不能空';
			} elseif (! $data ['url']) {
				$result ['status'] = 0;
				$result ['msg'] = 'url不能空';
			} elseif (! $data ['thumb']) {
				$result ['status'] = 0;
				$result ['msg'] = '请上传封面';
			} elseif ($this->checkUrl ( $data ['url'] )) {
				$result ['status'] = 0;
				$result ['msg'] = 'url已经存在';
			} else {
				$data ['updatetime'] = $data ['createtime'] = date ( 'Y-m-d H:i:s' );
				$data ['context'] = strip_tags ( preg_replace ( '/\s+style\=\"[^\"]*"/i', '', $data ['context'] ), '<p>,<strong>,<img>,<em>,<b>' );
				$data ['context'] = preg_replace ( '/\s+(?:height|width)=\d+\b/', '', $data ['context'] );
				$data ['photo'] = $this->_clearPhoto ( $data ['photo'] );
				$data ['intro'] = cut_str ( $data ['intro'], 200 );
				$rs = $this->add ( $data );
				if ($rs) {

					// 添加标签
					if ($data ['keyword'] != '') {
						$tags = make_tags ( $data ['keyword'] );
						$tag->saveData ( $tags ['tags'], $rs, 'site' );
					}

					$result ['status'] = 1;
					$result ['msg'] = '添加成功';
					$result ['id'] = $rs;
				} else {
					$result ['status'] = 0;
					$result ['msg'] = '添加失败';
				}
			}
		}
		return $result;
	}

	/**
	 * 获取单条信息
	 *
	 * @param unknown $id
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string>
	 */
	public function getInfo($id) {
		if (intval ( $id )) {
			$where = 'id=' . intval ( $id );
		} else {
			$where = 'url="' . $id . '"';
		}
		$result = $this->where ( $where )->find ();
		$result ['thumb500'] = C ( 'img_server' ) . str_replace ( '.', '_500_500.', $result ['thumb'] );
		$result ['thumb150'] = C ( 'img_server' ) . str_replace ( '.', '_150_150.', $result ['thumb'] );
		return $result;
	}
	/**
	 * 搜索列表
	 *
	 * @param number $where
	 * @param number $page
	 * @param string $order
	 * @param intval $num
	 *        	每页显示条数
	 * @return unknown
	 */
	public function search($where = 1, $page = 1, $order = '', $num = 12) {
		$page = intval ( $page ) < 1 ? 1 : $page;
		$result ['list'] = $this->where ( $where )->page ( $page, $num )->order ( $order )->select ();
		foreach ( $result ['list'] as $k => $v ) {
			$result ['list'] [$k] = $this->getInfo ( $v ['id'] );
		}
		$result ['total_num'] = $this->where ( $where )->count ();
		$result ['total_page'] = ceil ( $result ['total_num'] / $num );
		if ($result ['total_page'] > $page) {
			$result ['next_page'] = $page + 1;
		} else {
			$result ['next_page'] = '';
		}
		return $result;
	}

	/**
	 * 检查url是否存在
	 *
	 * @param unknown $url
	 * @param string $id
	 * @return unknown
	 */
	public function checkUrl($url, $id = '') {
		$where = 'url="' . $url . '"';
		if ($id) {
			$where .= ' and id!=' . intval ( $id );
		}
		$rs = $this->where ( $where )->count ();
		return $rs;
	}

	/**
	 * 删除操作(non-PHPdoc)
	 *
	 * @see \Think\Model::delete()
	 */
	public function delete($id) {
		$result ['msg'] = '删除失败';
		$result ['status'] = 0;
		if ($id) {
			// 检查是否有子信息

			// 删除
			$rs = M ( 'site' )->where ( 'id=' . intval ( $id ) )->delete ();
			;

			$result ['msg'] = '删除成功';
			$result ['status'] = 1;
		} else {
			$result ['msg'] = '删除失败';
			$result ['status'] = 0;
		}
		return $result;
	}

	/**
	 * 格式化图片
	 *
	 * @param unknown $str
	 */
	private function _clearPhoto($str) {
		$str = strip_tags ( $str, '<img>' );
		$str = preg_replace ( '/\s+style\=\"[^\"]*"/i', '', $str );
		$str = preg_replace ( '/\s+id\=\"[^\"]*"/i', '', $str );
		$str = preg_replace ( '/\s+class\=\"[^\"]*"/i', '', $str );
		$str = preg_replace ( '/\s+height\=\"[^\"]*"/i', '', $str );
		$str = preg_replace ( '/\s+width\=\"[^\"]*"/i', '', $str );
		$str = preg_replace ( '/\s+data\-[a-z]+\=\"[^\"]*"/i', '', $str );
		$pattern = '/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/i';
		preg_match_all ( $pattern, $str, $match );
		$str = implode ( '<br>', $match [0] );
		return $str;
	}

	/**
	 * 清除缓存
	 *
	 * @param unknown $id
	 */
	private function _clearInfoCache($id) {
		$info = $this->getInfo ( $id );

		$cacheName = get_cache_name ( 'site_' . $info ['id'] );
		S ( $cacheName, NULL );

		$cacheName = get_cache_name ( 'site_' . $info ['url'] );
		S ( $cacheName, NULL );
	}
}